package com.yss.netty.codec;

import com.yss.exception.RemotingException;
import com.yss.netty.protocol.Message;
import com.yss.netty.util.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Encoder
 */
public class NettyEncode extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        if (msg == null) {
            throw new RemotingException("Msg can not be null");
        }
        out.writeByte(Constants.MAGIC);
        out.writeByte(Constants.VERSION);
        out.writeLong(msg.getOpaque());
        out.writeByte(msg.getSerType().ordinal());
        out.writeByte(msg.getCommandType().ordinal());
        out.writeInt(msg.getBody().length);
        out.writeBytes(msg.getBody());
    }
}
